package com.me.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.me.entity.Config;
import com.me.service.ConfigService;
import com.me.util.EasyUIFormat;

@Controller
@RequestMapping("/config")
@SessionAttributes("startTime")
public class ConfigController extends BaseController {
	/**
	 * 注入业务组件
	 */
	@Resource
	private ConfigService configService;
	
	/**
	 * 跳转到config主页
	 */
	@RequestMapping("/index.do")
	public String toMember(){
		return "admin/main/config";
	}
	
	/**
	 * 查询所有admin
	 */
	@RequestMapping("/queryPage.do")
	@ResponseBody
	public Map<String, Object> queryAll(){
		List<Config> configs = configService.queryAll();
		return EasyUIFormat.formatEntities(configs);
	}
	
	/**
	 * 插入新记录
	 */
	@RequestMapping("/insert.do")
	@ResponseBody
	public Map<String, Object> insert(Config config){
		try {
			LOG.info("--------插入记录：" + config + "--------");
			configService.insert(config);
			return messageSuccess();
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "插入记录失败！");
		}
	}
	
	/**
	 * 修改记录
	 */
	@RequestMapping("/update.do")
	@ResponseBody
	public Map<String, Object> update(Config config){
		try {
			LOG.info("--------修改记录：" + config + "--------");
			configService.update(config);
			return messageSuccess();
		} catch (Exception e) {
			return messageFailure(e.getMessage(), "修改记录失败！");
		}
	}
	
	/**
	 * 获取考试终止时间
	 */
	@RequestMapping("/getEndTime.do")
	@ResponseBody
	public Map<String, Object> getEndTime(Model model, HttpSession session){
		// 此处可以接收到开考信号，记录开考时间，存入session中
		Long startTime = (Long) session.getAttribute("startTime");
		if(startTime == null){
			startTime = System.currentTimeMillis();
			model.addAttribute("startTime", startTime);
		}
		return messageSuccess(configService.getEndTime(startTime));
	}
}
